package org.ajaxgroovyshell.servlet;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONObject;

public class GroovyWriterServlet extends HttpServlet {
	
	private static final long serialVersionUID = -582036403708248146L;

	private static int seq = 0;
	byte[] buf = new byte[1000000];	
	
	@SuppressWarnings("unchecked")
	@Override
	protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException,
			IOException {
		long start = System.currentTimeMillis();
		JSONObject jsonObject = new JSONObject();
		int read = GroovyReaderServlet.consoleRunner.pis.read(buf, 0, 1000000);
		jsonObject.put("session", "bsVGwKuustmNJKQK3HL2gA");
		jsonObject.put("sequence", seq++);
		jsonObject.put("data", new String(buf, 0, read).replace("\n", "\r\n"));
		
		sendReply(jsonObject.toString(), response);
		long end = System.currentTimeMillis();
		System.out.println("Completed method in GroovyWriterServlet in " + (end - start));
	}
	
	@Override
	protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException,
			IOException {
		doPost(request, response);		
	}
	
	/**
	 * Write the response message to the output stream of the response. If the 
	 * responseEnvelope is null. The output stream will just be closed.
	 * 
	 * @param responseEnvelope
	 * @param response
	 * @throws IOException
	 */
	private void sendReply(String resp, final HttpServletResponse response) throws IOException{
		response.setContentType("Content-Type: application/json;charset=utf-8");
		final OutputStream outputStream = response.getOutputStream();
		try {			
			outputStream.write(resp.getBytes());
		} finally {
			outputStream.flush();
			outputStream.close();			
		}
	}
}
